package com.haiertvbic.tvnow.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;

import com.haiertvbic.tvnow.R;

public class MacAddress {
	private static final String TAG = "MacAddress";

	/**
	 * 
	 * @param plainText
	 *            要转成md5的文本
	 * @param Bway
	 *            转码的方式, 有32,和16两种,与pbs统一用32即可
	 * @return 返回md5加密后的文本
	 */
	public String Md5(String plainText, String Bway) {
		String md5mac = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			if (Bway.equals("32")) {
				// 32位的加密
				md5mac = buf.toString();
			} else if (Bway.equals("16")) {
				// 16位的加密
				md5mac = buf.toString().substring(8, 24);
			}

		} catch (NoSuchAlgorithmException e) {
			SLog.d(TAG, e.toString());
		}
		return md5mac;
	}

	/**
	 * 得到mac地址
	 * 
	 * @param context
	 * @return
	 */
	public String getMacAddress(Context context) {
		String result = "";
		String Mac = "";
		result = callCmd("busybox ifconfig", "HWaddr");

		// 如果返回的result == null，则说明网络不可取
		if (result == null) {
			String NOnetwork = context.getString(R.string.NOnetwork);
			return NOnetwork;
		}

		// 对该行数据进行解析
		// 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
		if (result.length() > 0 && result.contains("HWaddr") == true) {
			Mac = result.substring(result.indexOf("HWaddr") + 6,
					result.length() - 1);
			SLog.d(TAG, "Mac:" + Mac + " Mac.length: " + Mac.length());

			if (Mac.length() > 1) {
				Mac = Mac.replaceAll(" ", "");
				result = "";
				String[] tmp = Mac.split(":");
				for (int i = 0; i < tmp.length; ++i) {
					result += tmp[i];
				}
			}
			SLog.d(TAG, result + " result.length: " + result.length());
		}
		return result;
	}

	private String callCmd(String cmd, String filter) {
		String result = "";
		String line = "";
		try {
			Process proc = Runtime.getRuntime().exec(cmd);
			InputStreamReader is = new InputStreamReader(proc.getInputStream());
			BufferedReader br = new BufferedReader(is);

			// 执行命令cmd，只取结果中含有filter的这一行
			while ((line = br.readLine()) != null
					&& line.contains(filter) == false) {
				// result += line;
				SLog.d(TAG, "line: " + line);
			}

			result = line;
			SLog.d(TAG, "result: " + result);
		} catch (Exception e) {
			SLog.d(TAG, e.toString());
		}
		return result;
	}
}
